/*
 * Copyright 2002-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yb.xczx.security.resource.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;

/**
 * OAuth resource configuration.
 *
 * @author Josh Cummings
 */


//@Configuration
@Slf4j
@ComponentScan("com.yb.xczx.security.resource")
public class OAuth2JwtTokenConfig extends AbstractOauth2TokenSecurityConfig{

	@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
	String jwkSetUri;

	public OAuth2JwtTokenConfig(){
		log.info("OAuth2JwtTokenConfiguration");
	}




	@Override
	protected void resourceServerConfig(HttpSecurity http) throws Exception {
			http.oauth2ResourceServer(resourceServerConfigurer -> {
			resourceServerConfigurer.jwt(jwtConfigurer -> {
				JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
				JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
				jwtGrantedAuthoritiesConverter.setAuthorityPrefix("");
				jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("scope");
				jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
				jwtConfigurer.jwtAuthenticationConverter(jwtAuthenticationConverter);
			});
			resourceServerConfigurer.accessDeniedHandler(accessDeniedHandler());
			resourceServerConfigurer.authenticationEntryPoint(authenticationEntryPoint());
		});
	}

	@Bean
	JwtDecoder jwtDecoder() {
		return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
	}

}
